// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package operator

import (
	"fmt"
	"os"

	"github.com/kumose/errors"
	"github.com/kumose/kmopt/pkg/cluster/clusterutil"
	"github.com/kumose/kmopt/pkg/cluster/spec"
	"github.com/kumose/kmopt/pkg/utils"
)

// Download the specific version of a component from
// the repository, there is nothing to do if the specified version exists.
func Download(component, nodeOS, arch string, version string) error {
	if component == "" {
		return errors.New("component name not specified")
	}
	if version == "" {
		return errors.Errorf("version not specified for component '%s'", component)
	}

	resName := fmt.Sprintf("%s-%s", component, version)
	fileName := fmt.Sprintf("%s-%s-%s.tar.gz", resName, nodeOS, arch)
	targetPath := spec.ProfilePath(spec.KmoptPackageCacheDir, fileName)

	if err := utils.MkdirAll(spec.ProfilePath(spec.KmoptPackageCacheDir), 0755); err != nil {
		return err
	}

	repo, err := clusterutil.NewRepository(nodeOS, arch)
	if err != nil {
		return err
	}

	// Download from repository if not exists
	if utils.IsNotExist(targetPath) {
		if err := repo.DownloadComponent(component, version, targetPath); err != nil {
			return err
		}
	} else if version != "nightly" {
		if err := repo.VerifyComponent(component, version, targetPath); err != nil {
			os.Remove(targetPath)
		}
	}
	return nil
}
